package airthmetic.exercise.sort.cmp;


// 归并排序
public class _912_排序数组_Merge {
    int[] temp;

    public int[] sortArray(int[] nums) {
        if (nums.length < 2) {
            return nums;
        }
        temp = new int[nums.length];
        mergeSort(nums, 0, nums.length - 1);
        return nums;
    }

    private void mergeSort(int[] nums, int left, int right) {
        // terminal
        if (left == right) {
            return;
        }
        // process current logic
        int mid = ((right - left) >> 1) + left;
        // drill down
        mergeSort(nums, left, mid);
        mergeSort(nums, mid + 1, right);

        // 合并两个数组
        int i, j, k;
        i = left;
        j = mid + 1;
        k = 0;
        while (i <= mid && j <= right) {
            if (nums[i] <= nums[j]) {
                temp[k++] = nums[i++];
            } else {
                temp[k++] = nums[j++];
            }
        }

        while (i <= mid) {
            temp[k++] = nums[i++];
        }

        while (j <= right) {
            temp[k++] = nums[j++];
        }

        for (int m = right; m >= left; m--) {
            nums[m] = temp[--k];
        }
    }
}
